package cn.kailangtu.dataspot.services;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

import androidx.annotation.Nullable;

// 监控进程的 Service（独立进程）
public class NativeMonitorService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 定时检查主进程是否存在
        new Handler().postDelayed(() -> {
            if (!isMainProcessAlive()) {
                restartMainApp();
            }
        }, 5000); // 每5秒检查一次
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private boolean isMainProcessAlive() {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo proc : am.getRunningAppProcesses()) {
            if ("cn.kailangtu.dataspot:main".equals(proc.processName)) return true;
        }
        return false;
    }

    private void restartMainApp() {
        Intent launch = new Intent();
        launch.setComponent(new ComponentName("cn.kailangtu.dataspot", "cn.kailangtu.dataspot.activify.SplashActivity"));
        launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(launch);
    }
}